package com.company.myapplication.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieSyncManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;


import com.company.myapplication.R;
import com.company.myapplication.utils.CommentUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @auth: njb
 * @date: 2021/9/15 14:51
 * @desc: 商城页面
 */
public class MallActivity extends AppCompatActivity {
    private WebView mWebView;
    private String mallUrl = "";
    private String whChatPayUrl;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_mall);
    }

    protected void initView(Bundle savedInstanceState) {
        mWebView = findViewById(R.id.webView);
        mWebView.loadUrl(mallUrl);
        initWebView();
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        WebSettings settings = mWebView.getSettings();
        settings.setAllowFileAccess(true);
        settings.setJavaScriptEnabled(true); // 允许使用JavaScript
        settings.setSupportMultipleWindows(true);
        mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
        }
        // 缩放至屏幕的大小
        settings.setLoadWithOverviewMode(true);
        // 保存表单数据
        settings.setSaveFormData(true);
        // 是否应该支持使用其屏幕缩放控件和手势缩放
        settings.setSupportZoom(true);
        // 是否支持手势缩放控制
        settings.setBuiltInZoomControls(true);
        settings.setUseWideViewPort(true);
        settings.setSupportMultipleWindows(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        // 页面加载好以后，再放开图片
        settings.setBlockNetworkImage(false);
        // 启动应用缓存
        settings.setAppCacheEnabled(true);
        settings.setAppCacheMaxSize(Long.MAX_VALUE);
        // 使用localStorage则必须打开
        settings.setDomStorageEnabled(true);
        settings.setDatabaseEnabled(true);
        settings.setGeolocationEnabled(true);

        // WebView启用JavaScript执行。默认的是false。
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setAppCachePath(this.getDir("appcache", 0).getPath());
        settings.setDatabasePath(this.getDir("databases", 0).getPath());
        settings.setGeolocationDatabasePath(this.getDir("geolocation", 0).getPath());
        settings.setPluginState(WebSettings.PluginState.ON_DEMAND);
        CookieSyncManager.createInstance(this);
        CookieSyncManager.getInstance().sync();
        mWebView.setWebViewClient(new MallWebViewClient());
    }



    private class MallWebViewClient extends WebViewClient {
        String referer = "";

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith("http:") || url.startsWith("https:")) {
                return false;
            }
            whChatPayUrl = url;
            if (!TextUtils.isEmpty(url) && url.contains("showh5")) {//检测show5
                onBackPressed();
                return true;
            }
            try {
                Log.w("lzq", " outside wx:" + url);
                if (url.startsWith("alipays://")) {
                    if (CommentUtils.isAliPayInstalled(MallActivity.this)) {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_VIEW);
                        Log.w("lzq", " startWith wx:" + url);
                        intent.setData(Uri.parse(url));
                        startActivity(intent);
                        return true;
                    } else {
                        Toast.makeText(MallActivity.this,R.string.After_Sale_50,Toast.LENGTH_SHORT).show();
                        return false;
                    }
                }
                if (url.startsWith("weixin://")) {
                    if (CommentUtils.isWeChatInstalled(MallActivity.this)) {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_VIEW);
                        Log.w("lzq", " startWith wx:" + url);
                        intent.setData(Uri.parse(url));
                        startActivity(intent);
                        return true;
                    } else {
                        Toast.makeText(MallActivity.this,R.string.After_Sale_51,Toast.LENGTH_SHORT).show();
                        return false;
                    }
                } else {
                    Log.w("lzq", " contains wx:" + url);
                    if(CommentUtils.isWeChatInstalled(MallActivity.this)) {
                        Map<String, String> extraHeaders = new HashMap<>();
                        extraHeaders.put("Referer", referer);
                        view.loadUrl(url, extraHeaders);
                        return true;
                    }else {
                        return false;
                    }
                }
            } catch (Exception e) {
               e.printStackTrace();
            }
            return false;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, android.net.http.SslError error) {
            // 重写此方法可以让webview处理https请求
            handler.proceed();

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (null != whChatPayUrl) {
            if (whChatPayUrl.startsWith("weixin://wap/pay?") || whChatPayUrl.startsWith("https://wx.tenpay.com")) {
                mWebView.reload();
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                // 回退键 事件处理 优先级:视频播放全屏-网页回退-关闭页面
                if (mWebView.canGoBack()) {
                    mWebView.goBack();
                }
                return true;
            default:
                return super.onKeyUp(keyCode, event);
        }
    }
}
